#include "pix5core.h"


SafeFifo<Job*> ThreadMan::_jobs;
Array<JobRunner*> ThreadMan::_jobRunners;


static void* threadEntry(void* p)
{
	Thread* th = (Thread*)p;

	th->onThreadStart();

	return NULL;
}



void ThreadMan::init()
{
	for(int a=0;a<8;a++)
	{
		JobRunner* jr = new JobRunner();
		_jobRunners.add(jr);
		startThread(jr);
	}
}

void ThreadMan::shutdown()
{
	_jobs.abort();

	for(int a=0;a<8;a++)
	{
		JobRunner* jr = _jobRunners[a];
		joinThread(jr);
		delete jr;
	}

	_jobRunners.clear();
}

void ThreadMan::startThread(Thread* th)
{
	pthread_create(&th->_pth,NULL,threadEntry,th);
}

void ThreadMan::joinThread(Thread* th)
{
	pthread_join(th->_pth,NULL);
}


void ThreadMan::pushJob(Job* job)
{
	ASSERT(job->getJobState()==JS_NONE,"Invalid job state")

	job->setJobState(JS_QUEUED);
	_jobs.push(job);
}

Job* ThreadMan::popJob()
{
	return _jobs.popWait();
}

